<template>
  <px-form-item
    :label="label !== undefined ? label : '地块'"
    :prop="propValue"
    :rules="[{ required: isRequired, message: '地块不能为空', trigger: 'change' }]"
  >
    <px-select
      v-model="factoryAreaVal"
      :disabled="disabled"
      clearable
      filterable
      placeholder="请选择地块"
      style="width: 100%"
      @change="changeFactoryArea"
    >
      <px-option v-for="item in factoryAreaList" :key="item.id" :label="item.name" :value="item.value" />
    </px-select>
  </px-form-item>
</template>

<script setup lang="ts">
import { queryDictData } from "@/api/common";
import { computed, onMounted, ref, watch } from "vue";

// 父级方法和值
const emits = defineEmits(["changeFactoryArea"]);
const props = defineProps(["factoryArea", "isRequired", "disabled", "propValue", "defaultSelected", "label"]);

const factoryAreaVal = ref("");
const factoryAreaList = ref([]);
const disabled = computed(() => {
  return !!props.disabled;
});
const propValue = computed(() => {
  return props.propValue || "factoryAreaCode";
});

watch(
  () => props.factoryArea,
  val => {
    factoryAreaVal.value = props.factoryArea;
  },
  { immediate: true }
);
onMounted(() => {
  queryFactoryAreaSelect();
});
// 获取地块下拉列表
const queryFactoryAreaSelect = async () => {
  const tempFactoryAreaList = await queryDictData({ typeCode: "ERC_FACTORY_AREA" });
  factoryAreaList.value = tempFactoryAreaList || [];
  if (props.defaultSelected) {
    factoryAreaVal.value = tempFactoryAreaList[0]?.value;
    emits("changeFactoryArea", factoryAreaVal.value);
  }
};
// 改变地块值，传值给父级并做改变
const changeFactoryArea = () => {
  emits("changeFactoryArea", factoryAreaVal.value);
};
</script>
